<template>
   <div class="app-container">
      <splitpanes class=" menu-split">
         <pane min-size="15" size="15" style="padding-right: 20px;" class="menu-panel">
            <DeptTree ref="orgTreeRef" @dept-change="onDeptChange" @action-click="onActionClick" />
         </pane>
         <pane class="main-panel" :size="75" style="padding: 20px;">
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
               <el-form-item label="组织机构" prop="name">
                  <el-input v-model="queryParams.name" placeholder="请输入组织机构" clearable style="width: 200px"
                     @keyup.enter="handleQuery" />
               </el-form-item>
               <el-form-item label="状态" prop="isActive">
                  <el-select v-model="queryParams.isActive" placeholder="部门状态" clearable style="width: 200px">
                     <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                  </el-select>
               </el-form-item>
               <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
               </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
               <el-col :span="1.5">
                  <el-button-group>
                     <el-button type="warning" text bg icon="Download" @click="handleExport" v-hasFunc="'dept:export'">
                        导出
                     </el-button>
                     <el-button v-for="(btn, index) in enableOrgTypes" type="primary" text bg :key="index"
                        @click="handleAddOrg(btn.value)" v-hasFunc="'dept:add'">
                        <IconPlus :name="btn.icon" />
                        <span>{{ btn.label }}</span>
                     </el-button>
                  </el-button-group>
               </el-col>
               <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="deptList" row-key="id" highlight-current-row @row-click="onRowClick">
               <el-table-column prop="name" label="组织机构">
                  <template #default="{ row }">
                     <div class="icon-name">
                        <IconPlus v-if="orgIconMap && orgIconMap[row.type]" :name="orgIconMap[row.type]" />
                        <span>{{ row.name }}</span>
                     </div>
                  </template>
               </el-table-column>
               <el-table-column prop="code" label="组织编码"></el-table-column>
               <el-table-column prop="type" label="组织类型">
                  <template #default="{ row }">
                     <dict-tag :options="org_type" :value="row.type" />
                  </template>
               </el-table-column>
               <el-table-column prop="order" label="排序" width="200"></el-table-column>
               <el-table-column prop="isActive" label="状态" width="100">
                  <template #default="scope">
                     <dict-tag :options="sys_normal_disable" :value="scope.row.isActive" />
                  </template>
               </el-table-column>
               <el-table-column label="创建时间" align="center" prop="createdAt" width="200">
                  <template #default="scope">
                     <span>{{ parseTime(scope.row.createdAt) }}</span>
                  </template>
               </el-table-column>
               <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
                  <template #default="{ row }">
                     <div class="operate-cell">
                        <el-button link type="primary" icon="Edit" @click="handleUpdate(row)"
                           v-hasFunc="'dept:edit'">组织变更</el-button>
                        <el-dropdown @command="handleCommand($event, row)">
                           <el-button link type="primary">
                              更多操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                           </el-button>
                           <template #dropdown>
                              <el-dropdown-menu>
                                 <div v-hasFunc="'dept:del'">
                                    <el-dropdown-item command="handleDelete">
                                       <el-button link type="danger" icon="delete">删除</el-button>
                                    </el-dropdown-item>
                                 </div>
                                 <div v-hasFunc="'dept:type:edit'">
                                    <el-dropdown-item command="handleEditType">
                                       <el-button link icon="edit" type="primary">类型变更</el-button>
                                    </el-dropdown-item>
                                 </div>
                                 <div>
                                    <el-dropdown-item command="handleView">
                                       <el-button link icon="InfoFilled" type="primary">信息查看</el-button>
                                    </el-dropdown-item>
                                 </div>
                              </el-dropdown-menu>
                           </template>
                        </el-dropdown>
                     </div>
                  </template>
               </el-table-column>
            </el-table>
         </pane>
      </splitpanes>

      <!-- 添加或修改部门对话框 -->
      <DeptEdit ref="orgEditRef" :orgOptions="deptOptions" @onSuccess="onOrgEditClose" />
      <DeptTypeEdit ref="deptTypeRef" @onSuccess="onOrgEditClose" />
   </div>
</template>

<script setup name="Dept">
import { listDept, getDept, delDept, treeDeptList } from "@/api/system/dept";
import DeptTree from "./DeptTree.vue";
import DeptEdit from "./DeptEdit.vue";
import DeptTypeEdit from "./DeptTypeEdit.vue"
import { org_type } from "./dict"
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const deptList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const deptOptions = ref([]);
const parentDept = ref();
const currentOrg = ref();   //当前选中组织机构
const deptTypeRef = ref();
const orgEditRef = ref();
const orgTreeRef = ref();
const data = reactive({
   form: {},
   queryParams: {
      name: undefined,
      isActive: undefined,
      pid: undefined,
      pageIndex: 0,
      pageSize: 9999
   },
});

/**可选组织类型 */
const enableOrgTypes = computed(() => {
   if (parentDept.value?.id == '0') return [];
   return getSubOrgTypes(parentDept.value?.type)
})


const { queryParams, form } = toRefs(data);
const orgIconMap = Object.fromEntries(
   org_type.map(item => [item.value, item.icon])
);


// 子类型映射
const subTypeMapping = {
   GROUP: ['COMPANY', 'VIRTUAL'],
   COMPANY: ['DEPT', 'VIRTUAL'],
   DEPT: ['DEPT', 'TEAM', 'VIRTUAL'],
   TEAM: ['TEAM', 'VIRTUAL'],
   VIRTUAL: ["COMPANY", "DEPT", "TEAM", "VIRTUAL"]
};

/**
 * 根据传入的组织类型值获取其子类型对象
 * @param {string} typeValue - 组织类型的值
 * @returns {Array} - 子类型对象数组
 */
const getSubOrgTypes = (typeValue) => {
   const subTypeValues = subTypeMapping[typeValue] || [];
   return org_type.filter(org => subTypeValues.includes(org.value)) || [];
}


/** 查询部门列表 */
function getList() {
   loading.value = true;
   listDept(queryParams.value).then(response => {
      const { result } = response;
      deptList.value = result;
      loading.value = false;
   });
}

/** 表单重置 */
function reset() {
   form.value = {
      id: undefined,
      parentId: undefined,
      name: undefined,
      order: 0,
      leader: undefined,
      mobile: undefined,
      email: undefined,
      type: undefined,
      isActive: true
   };
   proxy.resetForm("deptRef");
}

/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pid = parentDept.value && parentDept.value.id;
   getList();
}

/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
}

/** 新增按钮操作 */
function handleAddOrg(type) {
   reset();
   form.value.type = type;
   let params = { pageSize: 9999 }
   listDept(params).then(response => {
      const { result } = response;
      deptOptions.value = proxy.handleTree(result, "id");
   });
   if (parentDept.value) {
      form.value.parentId = parentDept.value.id;
   }
   orgEditRef.value.setOrg(form.value);
   orgEditRef.value.addOrg();
}

/**添加顶级组织架构 */
const handleAddTopOrg = (type) => {
   reset();
   form.value.type = type;
   let params = { pageSize: 9999 }
   listDept(params).then(response => {
      const { result } = response;
      deptOptions.value = proxy.handleTree(result, "id");
   });
   orgEditRef.value.setOrg(form.value);
   orgEditRef.value.addOrg();
}

/**组织类型变更 */
const handleEditType = (row) => {
   deptTypeRef.value.setOrg(row);
}


/** 修改按钮操作 */
function handleUpdate(row) {
   reset();
   let treeParams = { includeSelf: false, selfId: row.id };

   treeDeptList(treeParams).then(response => {
      deptOptions.value = response;
   });

   getDept(row.id).then(response => {
      orgEditRef.value.setOrg(response);
      orgEditRef.value.editOrg();
   });
}

/** 删除按钮操作 */
const handleDelete = (row) => {
   proxy.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项?').then(function () {
      return delDept(row.id);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}


/**查看按钮操作 */
const handleView = (row) => {
   getDept(row.id).then(response => {
      orgEditRef.value.setOrg(response);
      orgEditRef.value.viewOrg();
   });
}

/**导出按钮操作 */
const handleExport = () => {
   proxy.download('system/dept/export', {
      ...queryParams.value
   }, `部门数据_${new Date().getTime()}.xlsx`);
}

//部门改变事件
const onDeptChange = (dept) => {
   parentDept.value = dept;
   currentOrg.value = undefined;
   handleQuery();
}

/**组织机构树点击事件 */
const onActionClick = (cmd, arg) => {
   switch (cmd) {
      case 'addOrg':
         handleAddTopOrg(arg);
         break;
      case 'editOrg':
         handleUpdate({ id: arg });
         break;
      default:
         break;
   }
}

/**行点击事件 */
const onRowClick = (row) => {
   currentOrg.value = row;
}

const handleCommand = (cmd, row) => {
   switch (cmd) {
      case 'handleDelete':
         handleDelete(row);
         break;
      case 'handleEditType':
         handleEditType(row);
         break;
      case 'handleView':
         handleView(row);
         break;
      default:
         break;
   }
}

/**组织类型编辑关闭 */
const onOrgEditClose = () => {
   getList();
   orgTreeRef.value.refresh();
}

onMounted(() => {
   orgTreeRef.value.initOrgTree();
})

</script>

<style lang="scss">
@import './index.scss';
</style>
